import { defineStore } from 'pinia'
import { ref } from 'vue'

// localStorage 键名常量
const STORAGE_KEYS = {
  NICKNAME: 'blog_comment_nickname',
  EMAIL: 'blog_comment_email',
  WEBSITE: 'blog_comment_website',
}

export const useCommentStore = defineStore('comment', () => {
  // 从 localStorage 初始化用户信息
  const nickname = ref(localStorage.getItem(STORAGE_KEYS.NICKNAME) || '')
  const email = ref(localStorage.getItem(STORAGE_KEYS.EMAIL) || '')
  const website = ref(localStorage.getItem(STORAGE_KEYS.WEBSITE) || '')

  // 其他状态
  const keyword = ref('')
  const tags = ref<string[]>([])

  // 设置昵称并持久化
  const setNickname = (nicknameValue: string) => {
    nickname.value = nicknameValue
    if (nicknameValue.trim()) {
      localStorage.setItem(STORAGE_KEYS.NICKNAME, nicknameValue)
    } else {
      localStorage.removeItem(STORAGE_KEYS.NICKNAME)
    }
  }

  // 设置邮箱并持久化
  const setEmail = (emailValue: string) => {
    email.value = emailValue
    if (emailValue.trim()) {
      localStorage.setItem(STORAGE_KEYS.EMAIL, emailValue)
    } else {
      localStorage.removeItem(STORAGE_KEYS.EMAIL)
    }
  }

  // 设置网址并持久化
  const setWebsite = (websiteValue: string) => {
    website.value = websiteValue
    if (websiteValue.trim()) {
      localStorage.setItem(STORAGE_KEYS.WEBSITE, websiteValue)
    } else {
      localStorage.removeItem(STORAGE_KEYS.WEBSITE)
    }
  }

  // 批量设置用户信息
  const setUserInfo = (userInfo: { nickname?: string; email?: string; website?: string }) => {
    if (userInfo.nickname !== undefined) {
      setNickname(userInfo.nickname)
    }
    if (userInfo.email !== undefined) {
      setEmail(userInfo.email)
    }
    if (userInfo.website !== undefined) {
      setWebsite(userInfo.website)
    }
  }

  // 清空用户信息
  const clearUserInfo = () => {
    nickname.value = ''
    email.value = ''
    website.value = ''
    localStorage.removeItem(STORAGE_KEYS.NICKNAME)
    localStorage.removeItem(STORAGE_KEYS.EMAIL)
    localStorage.removeItem(STORAGE_KEYS.WEBSITE)
  }

  // 获取用户信息对象
  const getUserInfo = () => ({
    nickname: nickname.value,
    email: email.value,
    website: website.value,
  })

  // 检查用户信息是否完整（昵称和邮箱是必需的）
  const isUserInfoComplete = () => {
    return nickname.value.trim() !== '' && email.value.trim() !== ''
  }

  return {
    // 状态
    nickname,
    email,
    website,
    keyword,
    tags,

    // 方法
    setNickname,
    setEmail,
    setWebsite,
    setUserInfo,
    clearUserInfo,
    getUserInfo,
    isUserInfoComplete,
  }
})
